package com.qianxx.network.Interceptor;

import android.text.TextUtils;

import com.qianxx.network.RetrofitRequestTool;
import com.qianxx.utils.SP;
import com.qianxx.utils.security.EncryptionUtil;
import com.socks.library.KLog;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created on 16/5/23 下午5:12.
 *
 * @author binwin20
 */
public class RequestInterceptor implements Interceptor {

    private static final String KEY_APPID = "appid";
    private static final String KEY_NONCESTR = "noncestr";
    private static final String KEY_SIGN = "sign";
    private static final String KEY_TOKEN = "token";

    private final SP mSP;

    public RequestInterceptor(SP SP) {
        mSP = SP;
    }

    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {

        // 添加头部 token 等
        final Request.Builder builder = chain.request().newBuilder();

        // 添加 签名等
        Request original = chain.request();
        if (original.method().equals("POST")) {
            FormBody.Builder newFormBody = new FormBody.Builder();
            // 参数的排序、加密
            SortMap sortMap = new SortMap();
            if (original.body() instanceof FormBody) {
                FormBody oidFormBody = (FormBody) original.body();
                for (int i = 0; i < oidFormBody.size(); i++) {
                    String key = oidFormBody.encodedName(i);
                    String value = oidFormBody.encodedValue(i);
                    if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                        newFormBody.addEncoded(key, value);
                        sortMap.put(URLDecoder.decode(key), URLDecoder.decode(value));
                    }
                }
            }
            // appid
            String appId = RetrofitRequestTool.getAppid();
            if (!TextUtils.isEmpty(appId)) {
                sortMap.put(KEY_APPID, appId);
                newFormBody.addEncoded(KEY_APPID, appId);
            }
            // nocestr
            String noncestr = "1";
            if (!TextUtils.isEmpty(noncestr)) {
                sortMap.put(KEY_NONCESTR, noncestr);
                newFormBody.addEncoded(KEY_NONCESTR, noncestr);
            }
            // token
            String token = RetrofitRequestTool.getToken(mSP);
            if (!TextUtils.isEmpty(token)) {
                sortMap.put(KEY_TOKEN, token);
                newFormBody.addEncoded(KEY_TOKEN, token);
            }
            // sign
            newFormBody.addEncoded(KEY_SIGN, getClientSign(sortMap));
            builder.method(original.method(), newFormBody.build());

            for (int i = 0; i < newFormBody.build().size(); i++) {
                KLog.e(newFormBody.build().encodedName(i) + " = " + URLDecoder.decode(newFormBody.build().encodedValue(i), "utf-8"));
            }
            KLog.e(URLDecoder.decode(original.url().toString(), "utf-8"));
        }

        return chain.proceed(builder.build());
    }

    private class SortMap extends TreeMap<String, String> {
        public SortMap() {
            super((obj1, obj2) -> -obj2.compareTo(obj1)); // 升序排序
        }
    }

    private static String getClientSign(Map<String, String> map) {
        StringBuilder params = new StringBuilder();
        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            String val = map.get(key);
            params.append(key);
            params.append("=");
            params.append(val);
            params.append("&");
        }
        params.append("key=" + RetrofitRequestTool.getKey());
        return EncryptionUtil.md5Encode(params.toString()).toUpperCase();
    }

}
